﻿using HengWang.OA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace HengWang.OA.Dal
{
    public class BaseDal<T> where T:class,new()
    {
        /// <summary>
        /// 拿到上下文
        /// </summary>
        public HengWangOADBEntities db
        {
            get
            {
                return DBHelper.Create();

            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public T Add(T t) {
            db.Set<T>().Add(t);
            db.SaveChanges();
            return t;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Update(T t)
        {
            db.Entry(t).State = System.Data.EntityState.Modified;

            return db.SaveChanges()>0;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Delete(T t)
        {
            db.Entry(t).State = System.Data.EntityState.Deleted;

            return db.SaveChanges() > 0;
        }
        /// <summary>
        /// 普通查询
        /// </summary>
        /// <param name="whereloamd"></param>
        /// <returns></returns>
        public IEnumerable<T> Select(Expression<Func<T,bool>>whereloamd) {
            return db.Set<T>().Where(whereloamd);
        }
        /// <summary>
        /// 单个查询
        /// </summary>
        /// <param name="whereloamd"></param>
        /// <returns></returns>
        public T Single(Expression<Func<T, bool>> whereloamd)
        {
            return db.Set<T>().FirstOrDefault(whereloamd);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="K"></typeparam>
        /// <param name="whereloamd"></param>
        /// <param name="orderbyloamd"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalcount"></param>
        /// <param name="pagecount"></param>
        /// <returns></returns>
        public IEnumerable<T> SelectPage<K>(Expression<Func<T, bool>> whereloamd, Expression<Func<T, K>> orderbyloamd, int pageindex, int pagesize, out int totalcount, out int pagecount)
        {
            var list = db.Set<T>().Where(whereloamd);
            totalcount = list.Count();
            pagecount = Convert.ToInt32(Math.Ceiling((double)totalcount / pagesize));
            return list.OrderBy(orderbyloamd).Skip((pageindex - 1) * pagesize).Take(pagesize);
        }
    }
}
